# 获取用户信息中间件
from pathlib import Path

from django.utils.deprecation import MiddlewareMixin

from BloodSpiderModel.DjangoResponseTool import response_dict

from BloodSpiderModel.spider_tools.file_operate import FileOperate

from BloodSpiderAPI import models

# 是否为不需要获取用户信息的URL
file_operate = FileOperate()
EXCLUDE_URLS = file_operate.json_format(file_operate.read_file(Path(__file__).parent.parent.parent / "PublicFunction" / "NeedPermissionURL.json"))



class GetUserInfoMiddleware(MiddlewareMixin):
    def process_request(self, request):
        try:
            user = models.User.objects.filter(user_id=request.META.get('HTTP_USER_ID')).first()
            for item in EXCLUDE_URLS:
                if item["url"] in request.path:
                    if item["role"] == 3:
                        
                        return None
                    elif item["role"] == 2:
                        if user:
                            request.user = user
                        else:
                            return response_dict.response_dict(message="用户ID不能为空", code=1)
                    elif item["role"] == 1 and request.path not in ['/api/user/create/']:
                        if not user:
                            return response_dict.response_dict(message="用户ID不能为空", code=1)
                        if user.role != 1:
                            return response_dict.response_dict(message="用户权限不足", code=1)
                    request.user = user
                    return None

            return None
        except Exception as e:
            return response_dict.response_dict(message=f"获取用户信息失败{e}", code=1)

        

        
       
        return None
    def process_response(self, request, response):

        return response
